#include <stdio.h>
#include "mystdio.h"
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

#define NEW_PERMISSON 0666
#define _EOF -1
  //这里设计三种模式，"w", "a", "r"
  _FILE* _fopen(const char*file, const char* mode)
  {
      int mod = 0;
      //以写的方式打开，并且如果文件不存在创建新文件,并且清空该文件夹
      if(strcmp(mode, "w") == 0)
        mod = O_WRONLY|O_CREAT|O_TRUNC;
      else if(strcmp(mode, "r") == 0)
        mod = O_RDONLY;
      else
        mod = O_WRONLY|O_CREAT|O_APPEND;
      int fd = open(file, mod, NEW_PERMISSON); 
      //打开之后，需要先判断是否正确打开
      if(fd == -1) return NULL;
      _FILE* pf = (_FILE*)malloc(sizeof (_FILE));
      pf->out_pos = 0;
    pf->flush_mode = ALL_REFRESH;
    pf->_fileno = fd;
    return pf;
}

int _fwrite(void* mesg, int sz,  _FILE* pf)
{
    //将数据内容写入到pf中
    int fd = pf->_fileno;
    int flush_mode = pf->flush_mode;
    int num = 0;
    if(flush_mode & NOW_REFRESH)
    {
        num = write(fd, mesg, sz); 
    }
    else if(flush_mode & LINE_REFRESH)
    {
      memcpy(&pf->outbuffer[pf->out_pos], (const char*)mesg, sz);
      pf->out_pos += sz;
      for(int i = pf->out_pos - 1; i >= 0; --i)
      {
        if(pf->outbuffer[i] == '\n')
        {
          num = write(fd, pf->outbuffer, i + 1);
          memmove(pf->outbuffer, pf->outbuffer + i + 1, pf->out_pos - i - 1);
          pf->out_pos = pf->out_pos - i - 1;
          printf("out_pos:%d\n", pf->out_pos);
        }
      }
    }
    else
    {
      memcpy(&pf->outbuffer[pf->out_pos], (const char*)mesg, sz);
      pf->out_pos += sz;
      if(pf->out_pos == MEMORY_SIZE)
      {
        write(fd, pf->outbuffer, MEMORY_SIZE);
        pf->out_pos = 0;
      }
    }
    return num;
}

int _fflush(_FILE* pf)
{
  if(!pf) return 1;
  write(pf->_fileno, pf->outbuffer, pf->out_pos);
  pf->out_pos = 0;
  return 0;
}

int _fclose(_FILE* pf)
{
    if(!pf) return _EOF;
    _fflush(pf);
    close(pf->_fileno);
    free(pf);
    return 0;
}
